package uscdb.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import uscdb.pageModel.Json;
import uscdb.service.ReviewServiceI;
import uscdb.util.ConfigUtil;
import uscdb.util.StringUtil.StringUtil;

@Controller
@RequestMapping("/reviewController")
public class ReviewController extends BaseController {

	private static final Logger logger = Logger.getLogger(ReviewController.class);

	@Autowired
	private ReviewServiceI reviewService;

	@ResponseBody
	@RequestMapping("/importReviewTask")
	public Json importReviewTask(HttpServletResponse response, HttpServletRequest request, HttpSession session) {
		Json json = new Json();
		try {
			// 文件保存目录路径
			String savePath = session.getServletContext().getRealPath("/") + "attached/import/";
			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("rarFile", ConfigUtil.get("rarFile"));
			long maxSize = Long.parseLong(ConfigUtil.get("maxFileSize")); // 允许上传最大文件大小(字节)
			if (!ServletFileUpload.isMultipartContent(request)) {
				json.setMsg("请选择文件！");
				return json;
			}
			// 检查目录
			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				uploadDir.mkdirs();
			}
			// 检查目录写权限
			if (!uploadDir.canWrite()) {
				json.setMsg("上传目录没有写权限！");
				return json;
			}
			// 增加日期目录，便于归档
			SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
			SimpleDateFormat monthDf = new SimpleDateFormat("MM");
			SimpleDateFormat dateDf = new SimpleDateFormat("dd");
			Date date = new Date();
			String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
			savePath += ymd;
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			if (ServletFileUpload.isMultipartContent(request)) {// 判断表单是否存在enctype="multipart/form-data"
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				try {
					List<FileItem> items = upload.parseRequest(request);
					// 上传的文件流
					File uploadedFile = null;
					for (FileItem item : items) {
						String fileName = item.getName();
						if (!item.isFormField()) {
							// 检查文件大小
							if (item.getSize() > maxSize) {
								json.setMsg("上传文件大小超过限制！(允许最大[" + maxSize + "]字节，您上传了[" + item.getSize() + "]字节)");
								return json;
							}
							// 检查扩展名
							String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
							if (!Arrays.<String> asList(extMap.get("rarFile").split(",")).contains(fileExt)) {
								json.setMsg(StringUtil.speakToUser("import"));
								return json;
							}

//							String newFileName = UUID.randomUUID().toString() + "." + fileExt;
							try {
								uploadedFile = new File(savePath, fileName);
								item.write(uploadedFile);
							} catch (Exception e) {
								logger.error(e.getMessage(), e);
								json.setMsg("上传文件失败！");
								return json;
							}
						}
					}
					String resultString = reviewService.importReviewTask(uploadedFile);
					json.setMsg(resultString);
					json.setSuccess(true);
				} catch (FileUploadException e) {
					logger.error(e.getMessage(), e);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setMsg("系统故障，请联系管理员");
		}
		return json;
	}
	
}
